"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 配置文件
Case Name   : 运行中删除配置文件
Create At   : 2020/06/29
Owner       : n@ningyali
Description :
    1.删除配置文件及其备份文件（若不删除备份文件，可修改配置参数成功并生产配置文件）
    2.修改配置参数
    3.恢复配置文件
    4.修改配置参数
Expect      :
    1.成功
    2.失败
    3.成功
    4.成功
History     :
    modified: 2020/12/20  modified by @peilinqian, postgresql.conf的备份文件安装完成默认为
    postgresql.conf.guc.bak，修改还原操作
    modified by @haomeng802 at 2022/12/27:修改还原postgresql.conf.guc.bak文件操作
"""

import os
import sys
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *


class DelConfFile(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case091.py start------------')
        self.conf_file_path = os.path.join(macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
        self.bak_file_path = os.path.basename(self.conf_file_path) + '.guc.bak'
        self.bak_path = macro.DB_BACKUP_PATH
        self.dbUserNode = Node(node='dbuser')
        self.com = Common()
        self.Constant = Constant()

    def test_del_conf_file(self):
        self.log.info('----------------------------运行中删除配置文件-----------------------------')
        try:
            # 获取主机hostname
            cmd = 'cat /etc/hostname'
            self.log.info(cmd)
            hostname = self.dbUserNode.sh(cmd).result()

            # 删除配置文件及其备份文件（若不删除备份文件，可修改配置参数成功并生成配置文件）
            self.bak_file = os.path.join(os.path.dirname(self.conf_file_path),
                                         self.bak_file_path)
            del_cmd = f'''
                        mkdir -p {self.bak_path}
                        mv {self.conf_file_path} {self.bak_path}; 
                        mv {self.bak_file} {self.bak_path}
                    '''
            self.log.info(del_cmd)
            del_msg = self.dbUserNode.sh(del_cmd).result()
            self.log.info(del_msg)
            self.assertEqual(del_msg, '')

            # 修改配置参数
            mod_msg = self.sh.executeGsguc('set', self.Constant.GSGUC_SUCCESS_MSG, 'max_connections = 800', hostname)
            self.log.info(mod_msg)
            self.assertFalse(mod_msg)

            # 恢复配置文件
            recover_cmd = f'''
                            mv {self.bak_path}/{os.path.basename(self.conf_file_path)} {os.path.dirname(self.conf_file_path)}; 
                            mv {self.bak_path}/{self.bak_file_path} {os.path.dirname(self.conf_file_path)}
                        '''
            self.log.info(recover_cmd)
            recover_msg = self.dbUserNode.sh(recover_cmd).result()
            self.log.info(recover_msg)
            self.assertEqual(recover_msg, '')

            # 修改配置参数
            mod_msg = self.sh.executeGsguc('set', self.Constant.GSGUC_SUCCESS_MSG, 'max_connections = 800', hostname)
            self.log.info(mod_msg)
            self.assertTrue(mod_msg)
        except Exception:
            self.log.info('恢复配置文件')
            recover_cmd = f'''
                            mv {self.bak_path}/{os.path.basename(self.conf_file_path)} {os.path.dirname(self.conf_file_path)}; 
                            mv {self.bak_path}/{self.bak_file_path} {os.path.dirname(self.conf_file_path)}
                            '''
            self.log.info(recover_cmd)
            recover_msg = self.dbUserNode.sh(recover_cmd).result()
            self.log.info(recover_msg)

    def tearDown(self):
        self.log.info('-----------------Opengauss_Reliability_Dbsys_Case091:执行完毕-----------------')
